
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserCacheManager {
  // 缓存头像
  static Future<String> cacheAvatar(String imageUrl) async {
    final file = await DefaultCacheManager().getSingleFile(imageUrl);
    return file.path;
  }

  // 保存用户信息
  static Future<void> saveUserInfo({
    String? userId,
    String? username,
    String? avatarURL,
    String? phone,
    String? sex,
    String? medicalRecord,
    DateTime? age

  }) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    if (userId != null) await prefs.setString('userId', userId);
    if (username != null) await prefs.setString('username', username);
    if (phone != null) await prefs.setString('phone', phone);
    if (sex != null) await prefs.setString('sex', sex);
    if (medicalRecord != null) await prefs.setString('medicalRecord', medicalRecord);
    if (age != null) await prefs.setString('age', age.toIso8601String());
    if(avatarURL != null) await prefs.setString('avatarURL', avatarURL);

  }

  // 读取用户信息
  static Future<Map<String, String>> getUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString('userId') ?? '未知';
    String username = prefs.getString('username') ?? '未知';
    String phone = prefs.getString('phone') ?? '未知';
    String sex = prefs.getString('sex') ?? '男';
    String medicalRecord = prefs.getString('medicalRecord') ?? '未知';
    String avatarURL = prefs.getString('avatarURL') ?? 'http://image.aiyuye.shop/AvatarURL/ic_launcher.png';

    return {'userId': userId, 'username': username, 'phone':phone, 'sex':sex, 'medicalRecord':medicalRecord, 'avatarURL':avatarURL};
  }

  // 读取用户生日<日期特殊化处理>
  static Future<DateTime?> loadDate() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String? age = prefs.getString('age');
    if (age != null) {
      return DateTime.parse(age); // 从字符串解析回 DateTime 对象
    }
    return null;
  }
}
